package com.bangcommunity.bbframe.monitor.collector;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;

import com.bangcommunity.bbframe.monitor.LogContextHelper;

/**
 * @author tanghc
 * @date 18/1/30
 */
public class CollectorHelper {
    private final static ConcurrentMap<String, AtomicReference<MLogRecordListBean>> recordsMap = new ConcurrentHashMap<>();

    public static void collect(String mkey, StatisticStateEnum stateEnum, Object result, Throwable throwable) {
        AtomicReference<MLogRecordListBean> reference = getReferenceInitIfNull(mkey);
        MLogRecordListBean current = reference.get();
        MLogRecordListBean update = new MLogRecordListBean();
        MLogRecordBean mLogRecordBean = new MLogRecordBean();
        mLogRecordBean.setLogContext(LogContextHelper.getLogContext(mkey));
        mLogRecordBean.setResult(result);
        mLogRecordBean.setThrowable(throwable);
        do {
            if (current == null) {
                update.add(mLogRecordBean);
            } else {
                update.addAll(current.getRecords());
            }
        } while (!reference.compareAndSet(current, update));

    }

    public static void report() {
        for (ConcurrentMap.Entry<String, AtomicReference<MLogRecordListBean>> entry : recordsMap.entrySet()) {
            String key = entry.getKey();
            AtomicReference<MLogRecordListBean> value = entry.getValue();

        }
    }

    private static AtomicReference<MLogRecordListBean> getReferenceInitIfNull(String mkey) {
        AtomicReference<MLogRecordListBean> reference = recordsMap.get(mkey);
        if (reference == null) {
            recordsMap.putIfAbsent(mkey, new AtomicReference<>());
            reference = recordsMap.get(mkey);
        }
        return reference;
    }
}
